package stc.skymobi.transport.protocol.esb.test;


import org.apache.commons.lang3.ArrayUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import stc.skymobi.bean.bytebean.core.BeanFieldCodec;
import stc.skymobi.bean.esb.core.TerminalAccessInfo;
import stc.skymobi.bean.esb.core.TerminalMessageHeader;
import stc.skymobi.bean.util.meta.Int2TypeMetainfo;
import stc.skymobi.transport.protocol.esb.ESBFixedHeader;
import stc.skymobi.transport.protocol.esb.codec.EsbSignalCodecUtils;
import stc.skymobi.util.ByteUtils;


public class EsbSignalCodecUtilsTestCase {

	private	BeanFieldCodec		beanCodec;
	private	Int2TypeMetainfo	metainfo;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
    		"stc/skymobi/transport/protocol/esb/test/esbBeanCodec.xml");

        beanCodec = (BeanFieldCodec)ctx.getBean("esbBeanCodec");
		
        ctx = new ClassPathXmlApplicationContext(
			"stc/skymobi/transport/protocol/esb/test/protocolMetainfo.xml");
        
        metainfo = (Int2TypeMetainfo)ctx.getBean("esbTypeMetainfo");
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testEsbA2MSignal() throws Exception {
		EsbA2MDemoSignal signal = new EsbA2MDemoSignal();
		
		signal.setSkyid(1);
		signal.setName("sky-mobi");
		signal.setDesc("hello,world!");
		
		TerminalAccessInfo tai = new TerminalAccessInfo();
		
		tai.setAccESBAddr(1);
		tai.setSkyId(100);
		tai.setAccSessioIndex(1000);
		
		signal.setTerminalAccessInfo(tai);
		
		TerminalMessageHeader msgHdr = new TerminalMessageHeader();
		
		msgHdr.setDstModule(1);
		msgHdr.setSrcModule(2);
		
		signal.setTerminalMessageHeader(msgHdr);
		
		signal.setDstESBAddr(1);
		signal.setSrcESBAddr(1);
		signal.setSeqNum(16);
		
		byte[] bytes = EsbSignalCodecUtils.encodeSignal(signal, beanCodec, 0);
		
		System.out.println( 
			ByteUtils.bytesAsHexString(bytes, 1024) );
		
		ESBFixedHeader hdr = EsbSignalCodecUtils.decodeSignalHeader(bytes, beanCodec);
		
		Assert.assertNotNull(hdr);

		System.out.println( "fixedHdr:" + hdr );
		
		byte[] bodyBytes = ArrayUtils.subarray(bytes, ESBFixedHeader.FIXED_HEADER_SIZE, bytes.length);
		
		EsbA2MDemoSignal signalDecoded = 
			(EsbA2MDemoSignal)EsbSignalCodecUtils.decodeSignalBody(hdr, bodyBytes, beanCodec, metainfo);
		
		Assert.assertEquals(signalDecoded, signal);
		
	}
	
}
